import { defineStore } from "pinia";
import defaultSettings from "@/settings";

export const useSettingsStore = defineStore("setting", () => {
    const title = defaultSettings.title;
    const version = defaultSettings.version;

    const tagView = useStorage<boolean>("tagView", defaultSettings.tagView);

    const showSettings = ref<boolean>(defaultSettings.showSettings);
    const sidebarLogo = ref<boolean>(defaultSettings.sidebarLogo);
    const sidebarBgTheme = useStorage<string>(
        "sidebarBgTheme",
        defaultSettings.sidebarBgTheme
    );
    const fixedHeader = useStorage<boolean>(
        "fixedHeader",
        defaultSettings.fixedHeader
    );
    const layout = useStorage<string>("layout", defaultSettings.layout);
    const themeColor = useStorage<string>(
        "themeColor",
        defaultSettings.themeColor
    );
    const theme = useStorage<string>("theme", defaultSettings.theme);

    // Whether to enable watermark
    const watermark = useStorage<any>("watermark", defaultSettings.watermark);

    const settingsMap: Record<string, Ref<any>> = {
        showSettings,
        fixedHeader,
        tagView,
        sidebarLogo,
        layout,
        themeColor,
        theme,
        watermark: watermark.value,
        sidebarBgTheme
    };

    function changeSetting ({ key, value }: { key: string; value: any }) {
        const setting = settingsMap[key];
        if (setting !== undefined) {
            setting.value = value;
            if (key === "theme") {
                if (value === "dark") {
                    document.documentElement.classList.add("dark");
                } else {
                    document.documentElement.classList.remove("dark");
                }
            }
        }
    }

    function changeSidebarBgTheme(theme: string) {
        sidebarBgTheme.value = theme;
    }

    return {
        title,
        version,
        showSettings,
        tagView,
        fixedHeader,
        sidebarLogo,
        layout,
        themeColor,
        changeSetting,
        theme,
        watermark,
        sidebarBgTheme,
        changeSidebarBgTheme
    };
},{ persist: true });
//persist: true 将当前数据保存在 localStorage
//使用useStorage时key相同会冲突，key 命名时一定要加前缀